<?php

defined('_JEXEC') or die('Restricted access');

class igFileHelper {

    function processUploadedImage($fileName, $tmpPath, $uploadError, $tableName, $refresh) {
        if (!$uploadedFile = igUploadHelper::upload_file($fileName, $tmpPath, $uploadError, IG_TEMP_PATH, $refresh)) {
            return false;
        }

        //get the folder path
        $increment = igFileHelper::getFileIncrement($tableName);
        $folderName = igFileHelper::getFolderName($increment);
        igFileHelper::makeFolder(IG_ORIG_PATH . DS . $folderName);
        $destFolderPath = IG_ORIG_PATH . DS . $folderName;

        //make the filename
        $destFile = igFileHelper::addIncrement($uploadedFile, $increment);
        $destFile = igFileHelper::checkUniqueName($destFolderPath, $destFile);

        //make the folder paths
        $sourcePath = IG_TEMP_PATH . DS . $uploadedFile;
        $destPath = $destFolderPath . DS . $destFile;

        if (!igFileHelper::makeImage($sourcePath, $destPath, 2000, 1500, 95, $refresh)) {
            return false;
        }

        $fileData = array();
        $fileData['filename'] = $destFile;

        $configArray = & JComponentHelper::getParams('com_igallery');

        if ($configArray->get('import_exif_data', 0) == 1) {
            $fileData['exif_des'] = JFilterOutput::cleanText(igFileHelper::getExifData($sourcePath));
        }

        if ($configArray->get('import_iptc_data', 0) == 1) {
            $fileData['iptc_des'] = JFilterOutput::cleanText(igFileHelper::getIptcData($sourcePath));
        }

        JFile::delete($sourcePath);

        return $fileData;
    }

    function processImportedImage($filePath) {
        $fullPath = $filePath;

        if (!igUploadHelper::checkExtension($fullPath, false)) {
            return false;
        }

        if (!igUploadHelper::checkMime($fullPath, false)) {
            return false;
        }

        $slash = strrpos($fullPath, DS) + 1;
        $filename = substr($fullPath, $slash);

        //get the folder path
        $increment = igFileHelper::getFileIncrement('igallery_img');
        $folderName = igFileHelper::getFolderName($increment);
        igFileHelper::makeFolder(IG_ORIG_PATH . DS . $folderName);
        $destFolderPath = IG_ORIG_PATH . DS . $folderName;

        //make the filename
        $destFile = igFileHelper::addIncrement($filename, $increment);
        $destFile = igFileHelper::checkUniqueName($destFolderPath, $destFile);
        $destPath = $destFolderPath . DS . $destFile;

        if (!igFileHelper::makeImage($fullPath, $destPath, 2000, 1500, 95, false)) {
            return false;
        }

        $fileData = array();
        $fileData['filename'] = $destFile;

        $configArray = & JComponentHelper::getParams('com_igallery');

        if ($configArray->get('import_exif_data', 0) == 1) {
            $fileData['exif_des'] = JFilterOutput::cleanText(igFileHelper::getExifData($fullPath));
        }

        if ($configArray->get('import_iptc_data', 0) == 1) {
            $fileData['iptc_des'] = JFilterOutput::cleanText(igFileHelper::getIptcData($fullPath));
        }

        return $fileData;
    }

    function originalToResized($fileName, $width, $height, $quality, $crop, $rotation, $round, $roundFill, $watermark=0, $wmText='', $wmTextColor='', $wmTextSize='', $wmFilename='', $wmPosition='', $wmTrans=100, $filesize=0) {
        $increment = igFileHelper::getIncrementFromFilename($fileName);
        $folderName = igFileHelper::getFolderName($increment);
        igFileHelper::makeFolder(IG_RESIZE_PATH . DS . $folderName);
        $fullFileName = igFileHelper::makeFileName($fileName, $width, $height, $quality, $crop, $rotation, $round, $roundFill, $watermark, $wmPosition, $wmTrans, $wmText, $wmTextColor, $wmTextSize, $wmFilename);

        $sourceFile = IG_ORIG_PATH . DS . $folderName . DS . $fileName;
        $destFile = IG_RESIZE_PATH . DS . $folderName . DS . $fullFileName;

        if (!igFileHelper::makeImage($sourceFile, $destFile, $width, $height, $quality, true, $crop, $rotation, $round, $roundFill, $watermark, $wmText, $wmTextColor, $wmTextSize, $wmFilename, $wmPosition, $wmTrans)) {
            return false;
        }

        $imgSize = getimagesize($destFile);

        $fileArray = array();
        $fileArray['fullFileName'] = $fullFileName;
        $fileArray['folderName'] = $folderName;
        $fileArray['width'] = $imgSize[0];
        $fileArray['height'] = $imgSize[1];

        if ($filesize == 1) {
            $size = filesize($destFile);
            $fileArray['filesize'] = $size;
        }

        return $fileArray;
    }

    function deleteImage($fileName, $deleteOrig) {
        $increment = igFileHelper::getIncrementFromFilename($fileName);
        $folderName = igFileHelper::getFolderName($increment);

        if ($deleteOrig) {
            $path = IG_ORIG_PATH . DS . $folderName . DS . $fileName;
            JFile::delete($path);
        }

        $OrigPattern = JFile::stripExt($fileName);
        $OrigPatternLength = strlen($OrigPattern);

        $resizedFolder = IG_RESIZE_PATH . DS . $folderName;
        $filesArray = JFolder::files($resizedFolder);

        for ($i = 0; $i < count($filesArray); $i++) {
            if (substr($filesArray[$i], 0, $OrigPatternLength) == $OrigPattern) {
                JFile::delete($resizedFolder . DS . $filesArray[$i]);
            }
        }
    }

    function getFileIncrement($tableName) {
        $db = & JFactory::getDBO();
        $prefix = $db->getPrefix();
        $query = "SHOW TABLE STATUS LIKE '" . $prefix . $tableName . "'";
        $db->setQuery($query);
        $row = $db->loadObject();
        return $row->Auto_increment;
    }

    function getIncrementFromFilename($fileName) {
        preg_match_all('/-[0-9]+/', $fileName, $matches);
        $last = array_pop($matches[0]);
        $increment = str_replace('-', '', $last);
        return $increment;
    }

    function getFolderName($folderRef) {
        $start = floor(($folderRef / 100) - 0.001) * 100;
        $end = ceil($folderRef / 100) * 100;
        $folderName = ( ($start ) + 1) . '-' . $end;

        return $folderName;
    }

    function makeFolder($folderPath) {
        jimport('joomla.filesystem.folder');

        if (!JFolder::exists($folderPath)) {
            if (!JFolder::create($folderPath, 0755)) {
                JError::raise(2, 500, $folderPath . ' ' . JText::_('FOLDER CREATE ERROR'));
                return false;
            }
        }
    }

    function makeFileName($fileName, $width, $height, $quality, $crop, $rotation, $round, $roundFill, $watermark, $wmPosition, $wmTrans, $wmText, $wmTextColor, $wmTextSize, $wmFilename) {
        jimport('joomla.filesystem.file');
        $fileNameExt = JFile::getExt($fileName);
        $fileNameNoExt = JFile::stripExt($fileName);

        $fullFileName = $fileNameNoExt . '-' . $width . '-' . $height . '-' . $quality;

        if ($crop == 1) {
            $fullFileName.= '-c';
        }

        if ($round == 1) {
            $fullFileName.= '-rd';

            if (preg_match("/jp/i", $fileNameExt)) {
                $fullFileName.= '-' . $roundFill;
            }
        }

        if ($rotation != 0) {
            $fullFileName.= '-r' . $rotation;
        }

        if ($watermark == 1 && ( strlen($wmFilename) > 1 || strlen($wmText) > 1)) {
            $fullFileName.= '-wm' . '-' . $wmPosition . '-' . $wmTrans;

            if (strlen($wmFilename) > 1) {
                $fullFileName.= '-' . preg_replace('/[^A-Za-z0-9]/', '', $wmFilename);
            }
            if (strlen($wmText) > 1) {
                $fullFileName.= '-' . preg_replace('/[^A-Za-z0-9]/', '', $wmText) . '-' . str_replace(',', '-', $wmTextColor) . '-' . $wmTextSize;
            }
        }

        $fullFileName .= '.' . $fileNameExt;

        return $fullFileName;
    }

    function addIncrement($file, $increment) {
        $fileNameExt = JFile::getExt($file);
        $fileNameNoExt = JFile::stripExt($file);

        return $fileNameNoExt . '-' . $increment . '.' . $fileNameExt;
    }

    function checkUniqueName($folderPath, $file) {
        if (JFile::exists($folderPath . DS . $file)) {
            $increment = igFileHelper::getIncrementFromFilename($file);
            $fileNameExt = JFile::getExt($file);
            $fileNameNoExt = JFile::stripExt($file);
            $fileNameNoIncrement = substr($fileNameNoExt, 0, strrpos($fileNameNoExt, '-'));

            $i = 1;
            while (JFile::exists($folderPath . DS . $fileNameNoIncrement . $i . '-' . $increment . '.' . $fileNameExt)) {
                $i++;
            }
            $file = $fileNameNoIncrement . $i . '-' . $increment . '.' . $fileNameExt;
        }

        return $file;
    }

    function getExifData($sourceFile) {
        $exifDescription = '';
        $ext = JFile::getExt($sourceFile);

        if (preg_match("/jp/i", $ext)) {

            $exifData = exif_read_data($sourceFile);
            $match = false;


            if (isset($exifData['ImageDescription'])) {
                if (strlen($exifData['ImageDescription']) > 0) {
                    $exifDescription = $exifData['ImageDescription'];
                    $match = true;
                }
            }

            if (isset($exifData['COMPUTED']['UserComment']) && $match == false) {
                if (strlen($exifData['COMPUTED']['UserComment']) > 0) {
                    $exifDescription = $exifData['COMPUTED']['UserComment'];
                    $match = true;
                }
            }

            if (isset($exifData['COMMENT'][0]) && $match == false) {
                if (strlen($exifData['COMMENT'][0]) > 0) {
                    $exifDescription = $exifData['COMMENT'][0];
                    $match = true;
                }
            }
        }

        $CleanExifDescription = JFilterOutput::cleanText($exifDescription);

        return $CleanExifDescription;
    }

    function getIptcData($sourceFile) {
        $iptcDescription = '';
        $size = getimagesize($sourceFile, $info);
        if (isset($info['APP13'])) {
            $iptc = iptcparse($info['APP13']);
            $match = false;

            if (isset($iptc['2#120'][0])) {
                if (strlen($iptc['2#120'][0]) > 0) {
                    $iptcDescription = $iptc['2#120'][0];
                    $match = true;
                }
            }
        }

        $CleanIptcDescription = JFilterOutput::cleanText($iptcDescription);
        return $CleanIptcDescription;
    }

    function makeImage($sourceFile, $destFile, $width, $height, $quality, $refresh, $crop=0, $rotation=0, $round=0, $roundFill='', $watermark=0, $wmText='', $wmTextColor='', $wmTextSize='', $wmFilename='', $wmPosition='', $wmTrans=100) {
        if ($width == 0 || $height == 0) {
            igFileHelper::raiseError('MI 1: ' . JText::_('IMAGE NOT ZERO'), $refresh);
            return false;
        }

        jimport('joomla.filesystem.file');
        require_once(JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_igallery' . DS . 'lib' . DS . 'wideimage' . DS . 'WideImage.php');

        //QUOCTUAN261 - & exists source file
        if (!JFile::exists($destFile) && JFile::exists($sourceFile)) {
            $ext = JFile::getExt($sourceFile);
            $imageinfo = getimagesize($sourceFile);
            $image = WideImage::load($sourceFile);

            if ($crop == 1 && $imageinfo[0] > $width && $imageinfo[1] > $height) {
                $image = $image->resize((int) $width, (int) $height, 'outside')->crop('center', 'middle', (int) $width, (int) $height);
            } else {
                $image = $image->resize((int) $width, (int) $height, 'inside', 'down');
            }

            if ($rotation != 0) {
                $image = $image->rotate($rotation, null, false);
            }

            if ($watermark == 1) {
                $positionArray = explode('_', $wmPosition);

                switch ($positionArray[0]) {
                    case 'left': $leftIndent = '+5';
                        break;
                    case 'right': $leftIndent = '-5';
                        break;
                    default: $leftIndent = '';
                }

                switch ($positionArray[1]) {
                    case 'top': $topIndent = '+5';
                        break;
                    case 'bottom': $topIndent = '-5';
                        break;
                    default: $topIndent = '';
                }

                if (strlen($wmText) > 0) {
                    $canvas = $image->getCanvas();
                    $fontPath = IG_ADMINISTRATOR_COMPONENT . DS . 'fonts' . DS . 'font.ttf';
                    $colorArray = explode(',', $wmTextColor);
                    $font = new WideImage_Font_TTF($fontPath, (int) $wmTextSize, $image->allocateColorAlpha((int) $colorArray[0], (int) $colorArray[1], (int) $colorArray[2], (100 - $wmTrans)));
                    $canvas->setFont($font);
                    $canvas->writeText($positionArray[0] . $leftIndent, $positionArray[1] . $topIndent, $wmText);
                }

                if (strlen($wmFilename) > 0) {
                    $extWatermark = JFile::getExt(IG_WATERMARK_PATH . DS . $wmFilename);
                    $overlay = WideImage::load(IG_WATERMARK_PATH . DS . $wmFilename);
                    $image = $image->merge($overlay, $positionArray[0], $positionArray[1], $wmTrans);
                }
            }

            if ($round == 1) {
                if ($width < 200) {
                    $radius = 11;
                } else {
                    $radius = 12;
                }

                $image = $image->roundCorners($radius, '0x' . $roundFill, 255);
            }

            if (preg_match("/jp/i", $ext)) {
                $image->saveToFile($destFile, $quality);
            } else {
                $image->saveToFile($destFile);
            }

            return true;
        }
        return true;
    }

    function raiseError($message, $refresh) {
        if ($refresh == null) {
            $task = JRequest::GetCmd('task', '');
            $refresh = $task == 'swfUpload' || $task == 'browserUpload' ? false : true;
        }

        if ($refresh == true) {
            JError::raise(2, 500, $message);
        } else {
            echo $message;
        }
    }

}